package com.offcn.service;

import com.offcn.pojo.Permission;
import com.offcn.pojo.Role;
import com.offcn.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpringSecurityUserService implements UserDetailsService {


    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询User
        User user = userService.getUserByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询角色
        List<GrantedAuthority> grantedAuthorityList=new ArrayList<>();

        List<Role> roleList = userService.getRolesByUserId(user.getId());
        for (Role role : roleList) {
            SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(role.getKeyword());
            grantedAuthorityList.add(simpleGrantedAuthority);
        }

        //查询权限
        List<Permission> permissionList = userService.getPermisionsByUserId(user.getId());
        for (Permission permission : permissionList) {
            SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(permission.getKeyword());
            grantedAuthorityList.add(simpleGrantedAuthority);
        }

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),grantedAuthorityList);
    }
}
